package software

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/hibiken/asynq"
	"log"
	"time"
)

const (
	TypeImageResize = "image:resize"
)

// asynq.Handler
// ProcessTask(context.Context, *Task) error

type ImageResizePayload struct {
	SourceURL string
}

func NewImageResizeTask(src string) (*asynq.Task, error) {
	payload, err := json.Marshal(ImageResizePayload{SourceURL: src})
	if err != nil {
		return nil, err
	}

	return asynq.NewTask(TypeImageResize, payload, asynq.MaxRetry(5), asynq.Timeout(20*time.Minute)), nil
}

func NewImageProcessor() *ImageProcessor {
	return &ImageProcessor{}
}

type ImageProcessor struct{}

func (processor *ImageProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
	var p ImageResizePayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	log.Printf("Resizing image: src=%s", p.SourceURL)

	return nil
}
